// You can use any data fetching library
import fetch from 'isomorphic-unfetch';
import Layout from '../components/MyLayout'
import Link from 'next/link'

// posts will be populated at build time by getStaticProps()
function Blog({ posts }) {
  return (
    <Layout>
      <h1>Batman TV Shows</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <Link href="/posts/[id]" as={`/posts/${post.id}`}>
              <a>{post.name}</a>
            </Link>
          </li>
        ))}
      </ul>
    </Layout>
  )
}

// This function gets called at build time on server-side.
// It won't be called on client-side, so you can even do
// direct database queries. See the "Technical details" section.
export async function getStaticProps(context) {
  console.log('---bloglist---getStaticProps---');
  // Call an external API endpoint to get posts.
  const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
  // console.log('res:',res);
  const posts = await res.json();
  // console.log('posts:',posts);

  // By returning { props: posts }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts: posts.map(x=>x.show),
    }
  }
}

export default Blog
